package com.lx.yygh.hosp.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.lx.yygh.common.exception.YyghException;
import com.lx.yygh.common.result.ResultCodeEnum;
import com.lx.yygh.hosp.repository.ScheduleRepository;
import com.lx.yygh.hosp.service.DepartmentService;
import com.lx.yygh.hosp.service.HospitalService;
import com.lx.yygh.hosp.service.ScheduleService;
import com.lx.yygh.model.hosp.BookingRule;
import com.lx.yygh.model.hosp.Department;
import com.lx.yygh.model.hosp.Hospital;
import com.lx.yygh.model.hosp.Schedule;
import com.lx.yygh.vo.hosp.BookingScheduleRuleVo;
import com.lx.yygh.vo.hosp.ScheduleOrderVo;
import com.mongodb.client.result.DeleteResult;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.joda.time.format.DateTimeFormat;
import org.springframework.beans.BeanUtils;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author c先生
 * @date 2022年10月16日 下午 1:13:40
 * @describe
 */
@Service
public class ScheduleServiceImpl implements ScheduleService {
    @Resource
    ScheduleRepository scheduleRepository;
    @Resource
    MongoTemplate mongoTemplate;
    @Resource
    HospitalService hospitalService;
    @Resource
    DepartmentService departmentService;

    @Override
    public void update(Schedule schedule) {
        Schedule save = scheduleRepository.save(schedule);
    }

    @Override
    public Boolean saveSchedule(Map<String, Object> map) {
        Schedule schedule = JSONObject.parseObject(JSONObject.toJSONString(map), Schedule.class);
        scheduleRepository.save(schedule);
        return true;
    }

    @Override
    public Page findPageSchedule(Integer page, Integer limit, Schedule schedule) {
        //pageable对象
        Pageable pageable= PageRequest.of(page-1,limit);
        //example:构建条件查询对象
        ExampleMatcher matcher = ExampleMatcher.matching().withStringMatcher(ExampleMatcher.StringMatcher.CONTAINING).withIgnoreCase();
        Example<Schedule> example = Example.of(schedule,matcher);
        Page pageModel = scheduleRepository.findAll(example, pageable);
        return pageModel;
    }

    @Override
    public Boolean deleteSchedule(String hosScheduleId) {
        Query query = new Query();
        query.addCriteria(Criteria.where("hosScheduleId").is(hosScheduleId));
        DeleteResult deleteResult = mongoTemplate.remove(query, Schedule.class);
        return deleteResult.wasAcknowledged();
    }

    @Override
    public Map<String, Object> getRuleSchedule(Long page, Long limit, String hoscode, String depcode) {
        //1、根据医院编号和科室编号进行查询
        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode);
        //2、Aggregation用于聚合操作
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(criteria),//匹配条件，相当于where
                Aggregation.group("workDate")//根据工作日期分组
                .first("workDate").as("workDate")
                //统计号源数量
                .count().as("docCount")
                .sum("availableNumber").as("availableNumber")
                .sum("reservedNumber").as("reservedNumber"),
                Aggregation.sort(Sort.Direction.ASC,"workDate"),//根据workDate进行排序
                //实现分页
                Aggregation.skip((page-1)*limit),
                Aggregation.limit(limit)
        );
        AggregationResults<BookingScheduleRuleVo> schedule = mongoTemplate.aggregate(aggregation, "Schedule", BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = schedule.getMappedResults();
        //获取总记录数(也就是)
        Aggregation aggregation2 = Aggregation.newAggregation(
                Aggregation.match(criteria),
                Aggregation.group("workDate")
        );

        AggregationResults<BookingScheduleRuleVo> schedule2 = mongoTemplate.aggregate(aggregation2, "Schedule", BookingScheduleRuleVo.class);
        int total = schedule2.getMappedResults().size();
        //获取日期对应的星期数
        for (BookingScheduleRuleVo bookingScheduleRuleVo : bookingScheduleRuleVoList) {
            Date date = bookingScheduleRuleVo.getWorkDate();
            DateTime dateTime = new DateTime(date).plusDays(-1);
            String dayOfWeek = getDayOfWeek(dateTime);
            bookingScheduleRuleVo.setDayOfWeek(dayOfWeek);
            bookingScheduleRuleVo.setWorkDate(dateTime.toDate());
        }

        Map<String,Object> result = new HashMap<>();
        result.put("bookingScheduleList",bookingScheduleRuleVoList);
        result.put("total",total);
        //获取医院名称
        String hosName = hospitalService.getHospName(hoscode);
        //其他基础数据
        Map<String, String> baseMap = new HashMap<>();
        baseMap.put("hosname",hosName);
        result.put("baseMap",baseMap);

        result.put("scheduleList",
                this.getScheduleDetail(hoscode,
                        depcode,
                        new SimpleDateFormat("yyyy-MM-dd").format(bookingScheduleRuleVoList.get(0).getWorkDate())));
        return result;
    }

    @Override
    public List<Schedule> getScheduleDetail(String hoscode, String depcode, String workDate) {

        /*SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date parseDate = null;
        try {
            parseDate = simpleDateFormat.parse(workDate);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (null == parseDate){
            return null;
        }
        Date dateNew = new Date(parseDate.getTime()+1000*60*60*24);
        Schedule schedule = new Schedule();
        schedule.setWorkDate(dateNew);
        Example<Schedule> of = Example.of(schedule);
        List<Schedule> list = scheduleRepository.findAll(of);*/

        DateTime dateTime = new DateTime(workDate);
        Date date = dateTime.plusHours(24).toDate();
        List<Schedule> scheduleList = scheduleRepository.findScheduleByHoscodeAndDepcodeAndWorkDate(hoscode,depcode,date);
        scheduleList.stream().forEach(item->{
            this.packageSchedule(item);
        });
        return scheduleList;
    }

    /**
     * 根据日期获取周几数据
     * @param dateTime
     * @return
     */
    private String getDayOfWeek(DateTime dateTime){
        String dayOfWeek = "";
        switch (dateTime.getDayOfWeek()){
            case DateTimeConstants.SUNDAY:
                dayOfWeek="周日";
                break;
            case DateTimeConstants.MONDAY:
                dayOfWeek="周一";
                break;
            case DateTimeConstants.TUESDAY:
                dayOfWeek="周二";
                break;
            case DateTimeConstants.WEDNESDAY:
                dayOfWeek="周三";
                break;
            case DateTimeConstants.THURSDAY:
                dayOfWeek="周四";
                break;
            case DateTimeConstants.FRIDAY:
                dayOfWeek="周五";
                break;
            case DateTimeConstants.SATURDAY:
                dayOfWeek="周六";
                break;
            default:
                break;
        }
        return dayOfWeek;
    }
    //封装排班详情其他值 医院名称、科室名称、日期对应星期
    private void packageSchedule(Schedule schedule) {
        //设置医院名称
        schedule.getParam().put("hosname",hospitalService.getHospName(schedule.getHoscode()));
        //设置科室名称
        schedule.getParam().put("depname",departmentService.getDepName(schedule.getHoscode(),schedule.getDepcode()));
        //设置日期对应星期
        schedule.getParam().put("dayOfWeek",this.getDayOfWeek(new DateTime(schedule.getWorkDate())));
    }

    /**
     * 将Date日期（yyyy-MM-dd HH:mm）转换为DateTime
     */
    private DateTime getDateTime(Date date, String timeString) {
        String dateTimeString = new DateTime(date).toString("yyyy-MM-dd") + " "+ timeString;
        DateTime dateTime = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm").parseDateTime(dateTimeString);
        return dateTime;
    }

    @Override
    public Map<String, Object> getBookingScheduleRule(int page, int limit, String hoscode, String depcode) {//传过来分页数据和查询条件
        Map<String,Object> result = new HashMap<>();//包含bookingScheduleList  total  baseMap
        //获取预约规则
        //根据医院编号获取预约规则
        Hospital hospital = hospitalService.getHospitalByHoscode(hoscode);
        if(hospital==null){
            throw new YyghException(ResultCodeEnum.DATA_ERROR);
        }
        BookingRule bookingRule = hospital.getBookingRule();
        //获取可预约日期的数据（分页）
        IPage iPage = this.getListDate(page,limit,bookingRule);
        //当前可预约日期
        List<Date> dateList = iPage.getRecords();

        //获取可预约日期里面科室的剩余预约数 mongodb
        Criteria criteria = Criteria.where("hoscode").is(hoscode).and("depcode").is(depcode).and("workDate").in(iPage.getRecords());

        //根据workDate进行分组
        Aggregation aggregation = Aggregation.newAggregation(
                Aggregation.match(criteria),//匹配条件
                Aggregation.group("workDate")//分组条件
                        .first("workDate").as("workDate")
                        //统计号源数量
                        .count().as("docCount")
                        .sum("reservedNumber").as("reservedNumber")
                        .sum("availableNumber").as("availableNumber")
        );
        AggregationResults<BookingScheduleRuleVo> aggregate = mongoTemplate.aggregate(aggregation, Schedule.class, BookingScheduleRuleVo.class);
        List<BookingScheduleRuleVo> bookingScheduleList = aggregate.getMappedResults();
        //把list转化为map，以workDate为key，BookingScheduleRuleVo为valus
        Map<Date, BookingScheduleRuleVo> scheduleVoMap = new HashMap<>();
        if(!CollectionUtils.isEmpty(bookingScheduleList)) {
            scheduleVoMap = bookingScheduleList.stream()
                    .collect(
                            Collectors.toMap(
                                    BookingScheduleRuleVo::getWorkDate,
                                    (BookingScheduleRuleVo b)->b) );
        }
        //获取可预约排班规则
        List<BookingScheduleRuleVo> bookingScheduleRuleVoList = new ArrayList<>();
        for(int i = 0, len=dateList.size(); i < len; i++){
            Date date = dateList.get(i);
            //从scheduleVoMap集合中根据key的值获取BookingScheduleRuleVo
            BookingScheduleRuleVo bookingScheduleRuleVo = scheduleVoMap.get(date);
            //如果当天没有排班医生
            if(bookingScheduleRuleVo==null){
                bookingScheduleRuleVo = new BookingScheduleRuleVo();
                //就诊医生人数
                bookingScheduleRuleVo.setDocCount(0);
                //科室剩余预约数  -1表示无号
                bookingScheduleRuleVo.setAvailableNumber(-1);
            }
            bookingScheduleRuleVo.setWorkDate(date);
            bookingScheduleRuleVo.setWorkDateMd(date);
            bookingScheduleRuleVo.setDayOfWeek(getDayOfWeek(new DateTime(date)));
            //最后一页最后一条记录为即将预约   状态 0：正常 1：即将放号 -1：当天已停止挂号
            if(i == len-1 && page == iPage.getPages()){
                bookingScheduleRuleVo.setStatus(1);
            }else {
                bookingScheduleRuleVo.setStatus(0);
            }
            //当天预约如果过了停号时间， 不能预约
            if(i == 0 && page == 1){
                String stopTimeStr = bookingRule.getStopTime();
                DateTime stopTime = this.getDateTime(date, stopTimeStr);
                if(stopTime.isBeforeNow()){
                    bookingScheduleRuleVo.setStatus(-1);
                }
            }
            bookingScheduleRuleVoList.add(bookingScheduleRuleVo);
        }
        //可预约日期规则数据
        result.put("bookingScheduleList", bookingScheduleRuleVoList);
        result.put("total", iPage.getTotal());
        //其他数据
        HashMap<String, Object> baseMap = new HashMap<>();
        baseMap.put("hosname",hospitalService.getHospName(hoscode));
        Department department =departmentService.getDepartment(hoscode, depcode);
        baseMap.put("bigname",department.getBigname());
        baseMap.put("depname",department.getDepname());

        baseMap.put("workDateString",new DateTime().toString("yyyy年MM月"));
        baseMap.put("releaseTime",bookingRule.getReleaseTime());
        baseMap.put("stopTime", bookingRule.getStopTime());
        result.put("baseMap",baseMap);
        return result;
    }

    private IPage getListDate(int page, int limit, BookingRule bookingRule) {
        //获取当天放号时间 yyyy-MM-dd HH:mm
        DateTime releaseTime = this.getDateTime(new Date(),bookingRule.getReleaseTime());

        //获取预约周期
        Integer cycle = bookingRule.getCycle();
        //如果当天的放号时间已经过去了，那么预约周期加一天
        if(releaseTime.isBeforeNow()){
            cycle = cycle+1;
        }

        //获取所有可预约日期
        List<Date> dateList = new ArrayList<>();
        for(int i = 0; i < cycle; i++){
            DateTime dateTime = new DateTime().plusDays(i);
            //格式化日期，去掉后面的时分秒
            String dateString = dateTime.toString("yyyy-MM-dd");
            dateList.add(new DateTime(dateString).toDate());
        }
        //因为预约周期不同的，每页显示日期最多7天数据，超过7天分页
        List<Date> pageDateList = new ArrayList<>();
        int startIndex = (page-1)*limit;
        int endIndex = (page-1)*limit+limit;//limit等于7
        //如果可以显示数据小于7，直接显示
        if(endIndex > dateList.size()){
            endIndex = dateList.size();
        }
        for(int i = startIndex; i < endIndex; i++) {
            pageDateList.add(dateList.get(i));
        }
        //造出分页数据
        IPage<Date> iPage = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(page,limit,dateList.size());
        iPage.setRecords(pageDateList);
        return iPage;
    }

    @Override
    public Schedule getScheduleById(String scheduleId) {
        Optional<Schedule> optionalSchedule = scheduleRepository.findById(scheduleId);
        Schedule schedule = optionalSchedule.get();
        this.packageSchedule(schedule);
        return schedule;
    }

    @Override
    public ScheduleOrderVo getScheduleOrderVo(String scheduleId) {
        Optional<Schedule> optionalSchedule = scheduleRepository.findById(scheduleId);
        Schedule schedule = optionalSchedule.get();
        if(null == schedule) {
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        ScheduleOrderVo scheduleOrderVo = new ScheduleOrderVo();
        BeanUtils.copyProperties(schedule,scheduleOrderVo);
        //获取预约规则信息
        Hospital hospital = hospitalService.getHospitalByHoscode(scheduleOrderVo.getHoscode());
        if(null == hospital) {
            throw new YyghException(ResultCodeEnum.DATA_ERROR);
        }
        BookingRule bookingRule = hospital.getBookingRule();
        if(null == bookingRule) {
            throw new YyghException(ResultCodeEnum.PARAM_ERROR);
        }
        scheduleOrderVo.setHoscode(schedule.getHoscode());
        scheduleOrderVo.setHosname(hospitalService.getHospitalByHoscode(schedule.getHoscode()).getHosname());
        scheduleOrderVo.setDepcode(schedule.getDepcode());
        scheduleOrderVo.setDepname(departmentService.getDepartment(schedule.getHoscode(), schedule.getDepcode()).getDepname());
        scheduleOrderVo.setHosScheduleId(schedule.getHosScheduleId());
        scheduleOrderVo.setAvailableNumber(schedule.getAvailableNumber());
        scheduleOrderVo.setTitle(schedule.getTitle());
        scheduleOrderVo.setReserveDate(schedule.getWorkDate());
        scheduleOrderVo.setReserveTime(schedule.getWorkTime());
        scheduleOrderVo.setAmount(schedule.getAmount());

        //退号截止天数（如：就诊前一天为-1，当天为0）
        int quitDay = bookingRule.getQuitDay();
        DateTime quitTime = this.getDateTime(new DateTime(schedule.getWorkDate()).plusDays(quitDay).toDate(), bookingRule.getQuitTime());
        scheduleOrderVo.setQuitTime(quitTime.toDate());
        //预约开始时间
        DateTime startTime = this.getDateTime(new Date(),bookingRule.getReleaseTime());
        scheduleOrderVo.setStartTime(startTime.toDate());
        //预约截止时间
        DateTime endTime = this.getDateTime(new DateTime().plusDays(bookingRule.getCycle()).toDate(), bookingRule.getStopTime());
        scheduleOrderVo.setEndTime(endTime.toDate());
        //当天停止挂号时间
        DateTime stopTime = this.getDateTime(new Date(), bookingRule.getStopTime());
        scheduleOrderVo.setStartTime(startTime.toDate());
        return scheduleOrderVo;
    }
}
